package ch.fusun.baron.weather;

/**
 * Updates the vapor distribution
 */
public class VaporUpdater implements AutomatonUpdater {

	private final int altitude;

	/**
	 * Constructor
	 * 
	 * @param altitude
	 */
	public VaporUpdater(int altitude) {
		this.altitude = altitude;
	}

	@Override
	public void update(Cube[][][] surroundingCubes, Cube cube) {
		float vaporDiff = 0;
		Cube oldCube = surroundingCubes[1][1][1];
		for (Cube[][] surroundingCube : surroundingCubes) {
			for (Cube[] elements : surroundingCube) {
				for (Cube child : elements) {
					boolean topWrapAround = (child.getZ() == 0)
							&& (oldCube.getZ() == altitude - 1);
					boolean bottomWrapAround = (child.getZ() == altitude - 1)
							&& (oldCube.getZ() == 0);

					boolean wrapAround = topWrapAround && bottomWrapAround;
					if (!wrapAround) {
						if (oldCube.getTemperature() < child.getTemperature()) {
							if (child.getTemperature() > 0) {
								vaporDiff += (1.0f - oldCube.getTemperature()
										/ child.getTemperature())
										* child.getVapour();
							}
						} else {
							if (oldCube.getTemperature() > 0) {
								vaporDiff -= (1.0f - child.getTemperature()
										/ oldCube.getTemperature())
										* oldCube.getVapour();
							}
						}
					}
				}
			}
		}
		cube.setVapour(oldCube.getVapour() + (vaporDiff / 27.0f));
	}
}
